﻿#ifndef _C_RTSPSERVER_H_INCLUDE_
#define _C_RTSPSERVER_H_INCLUDE_

#include "rtsp_common.h"
#include "h264source.h"

#include <QTcpServer>
#include <QHash>
#include <QMutex>
#include <QImage>

class CRtspClient;

class CRtspServer : public QTcpServer
{
    Q_OBJECT

public:
    explicit CRtspServer(QObject *parent = nullptr);
    ~CRtspServer();

    /// 打开一个指定端口的服务器
    Q_INVOKABLE bool OpenServer(int port=1935);
    /// 关闭服务器
    Q_INVOKABLE void CloseServer(void);
    /// 初始化h264
    void initH264(QSize screenSize);
    /// 卸载h264
    void clearnH264(void);
    /// 添加一个客户端到群中
    bool addClientToGroup(CRtspClient *client);

    /// 处理图片
    bool HandleImage(QImage& image);
    /// 处理视频帧
    bool HandleFrame(AVFrame *frame);
    /// 处理视频帧到群
    bool HandleFrameGroup(QString suffix,QByteArray* frame);

signals:
    /// 日志消息
    void sockLog(QString log);

private slots:
    /// 日志消息
    void sockLogSlot(QString log);
    void sockConnectSlot(qintptr conn);
    void sockDisConnectSlot(qintptr conn);
    /// 处理网络二进制消息
    void sockBinMessageSlot(qintptr conn,QByteArray data);

private:
    void incomingConnection(qintptr socketDescriptor);
    /// 清除所有的客户端
    void deleteAllClients(void);
    /// 清除指定的客户端
    void deleteClient(qintptr socketDescriptor);
    /// 处理YUV240P数据
    bool HandleYuv240PFrame(unsigned char* yuvData);

private:
    QMutex mclientMutex;
    QHash<qintptr, CRtspClient*> mtcpClients;               /**< 管理连接的map */
    quint8 *mimageBuffer;                                   /**< 图片转换缓冲区 */
    QHash<QString, RtspGroup> mGroups;                      /**< 管理所有的用户组 */
};

#endif // CRTSPSERVER_H
